package com.trivia

class ScoreService {

    static transactional = true

    def saveScore(Level level, AppUser user, int correctAnswers, int incorrectAnswers, int notAnswers, long time) {
		
		validateQuestionQuantity(level.questionQuantity, correctAnswers + incorrectAnswers + notAnswers)
		int scoring = calculateScoring(correctAnswers, incorrectAnswers)
		
		println "scoring: " + scoring;
		
		Score score = new Score(level:level,appUser:user,scoring:scoring,time:time)
		score.save()
		
		user.addToScores(score)
		
		user.save()
		
		score
    }
	
	def private calculateScoring(int correctAnswers, int incorrectAnswers){
		//TODO Pasar esto a alguna tabla de configuracion y ver como hacer el calculo de los bonus
		(correctAnswers * 2) + (incorrectAnswers * -1)
	}
	
	def private validateQuestionQuantity(int levelQuantity, int resultQuantity){		
		if (levelQuantity != resultQuantity)
			throw new Exception("Cantidad de preguntar invalida.")		
			
		println "paso la validacion"
	}
}
